package cn.ultrarisk.scadmin.manager.biz.solr.service;

import cn.ultrarisk.mybatis.extension.query.Query;
import cn.ultrarisk.mybatis.extension.query.Updater;
import cn.ultrarisk.scadmin.manager.biz.solr.dao.SolrCacheDAO;
import cn.ultrarisk.scadmin.manager.biz.solr.entity.SolrCache;
import cn.ultrarisk.scadmin.manager.util.JsonUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

/**
 * SolrCacheService
 *
 * @author sevendlong(lin23871@163.com)
 * @date 2014/5/13
 * @since V1.0
 */
@Service
@Transactional(propagation = Propagation.NOT_SUPPORTED)
public class SolrCacheService {
    @Autowired
    private SolrCacheDAO solrCacheDAO;

    public SolrCache saveBySolrInfo(Integer replicaId, String cacheType, JsonUtil.MapWrapper cacheMap, Long updateTime) {
        SolrCache cache = solrCacheDAO.get(Query.query(SolrCache.REPLICA_ID, replicaId).eq(SolrCache.CACHE_TYPE, cacheType));
        String cacheClass = cacheMap.getStringByPath("class");
        String cacheVersion = cacheMap.getStringByPath("version");
        String cacheDescription = cacheMap.getStringByPath("description");

        if (cache == null) {
            cache = new SolrCache(replicaId, cacheType);
        }

        cache.setCacheClass(cacheClass);
        cache.setCacheVersion(cacheVersion);
        cache.setCacheDescription(cacheDescription);
        cache.setUpdateTime(updateTime);

        if (cache.getId() == null) {
            solrCacheDAO.create(cache);
        } else {
            solrCacheDAO.update(cache.getId(), Updater.update(SolrCache.CACHE_CLASS, cacheClass).addField(SolrCache.CACHE_VERSION, cacheVersion)
                    .addField(SolrCache.CACHE_DESCRIPTION, cacheDescription).addField(SolrCache.UPDATE_TIME, updateTime));
        }
        return cache;
    }

    /**
     * 清除过期的solrCache
     *
     * @query expiredTime
     */
    public void clearExpiredData(long expiredTime) {
        Query query = Query.ltQuery(SolrCache.UPDATE_TIME, expiredTime);
        solrCacheDAO.delete(query);
    }
}
